package com.huirui.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.context.UserContext;
import com.huirui.server.mapper.DeliveryAddressMapper;
import com.huirui.server.pojo.dto.DeliveryAddressDTO;
import com.huirui.server.pojo.entity.DeliveryAddress;
import com.huirui.server.pojo.vo.DeliveryAddressVo;
import com.huirui.server.service.DeliveryAddressService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author yujun
 * @description 针对表【t_delivery_address(用户收货地址表)】的数据库操作Service实现
 * @createDate 2025-09-14 16:58:34
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DeliveryAddressServiceImpl extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress>
        implements DeliveryAddressService {

    private final ResourceLoader resourceLoader;

    @Override
    public List<DeliveryAddressVo> listUserAddress() {
        Long userId = UserContext.getId();
        List<DeliveryAddress> list = lambdaQuery()
                .eq(DeliveryAddress::getUserId, userId)
                .orderByDesc(DeliveryAddress::getIsDefault)
                .orderByDesc(DeliveryAddress::getUpdatedTime)
                .list();
        return list.stream().map(deliveryAddress -> {
            DeliveryAddressVo addressVo = new DeliveryAddressVo();
            BeanUtils.copyProperties(deliveryAddress, addressVo);
            return addressVo;
        }).toList();
    }

    @Override
    public void save(DeliveryAddressDTO addressDTO) {
        DeliveryAddress deliveryAddress = new DeliveryAddress();
        BeanUtils.copyProperties(addressDTO, deliveryAddress);
        deliveryAddress.setCreatedTime(LocalDateTime.now());
        deliveryAddress.setUpdatedTime(LocalDateTime.now());
        deliveryAddress.setUserId(UserContext.getId());
        Long count = lambdaQuery().eq(DeliveryAddress::getUserId, UserContext.getId()).count();
        if (count == 0) {
            deliveryAddress.setIsDefault(1);
        }
        if (deliveryAddress.getIsDefault() == 1) {
            lambdaUpdate()
                    .eq(DeliveryAddress::getUserId, UserContext.getId())
                    .set(DeliveryAddress::getIsDefault, 0)
                    .update();
        }
        super.save(deliveryAddress);
    }

    @Override
    public void deleteDeliveryAddressById(Long id) {
        Long userId = UserContext.getId();
        // 查询删除的是否为默认地址
        Integer isDefault = lambdaQuery()
                .select(DeliveryAddress::getIsDefault)
                .eq(DeliveryAddress::getId, id)
                .one().getIsDefault();
        removeById(id);
        // 不是默认地址删除后直接返回
        if (isDefault == 0) return;
        // 否则将最近更新的地址设置为默认地址
        DeliveryAddress address = lambdaQuery()
                .eq(DeliveryAddress::getUserId, userId)
                .orderByDesc(DeliveryAddress::getUpdatedTime)
                .last("LIMIT 1")
                .one();
        if (address == null) return;
        address.setIsDefault(1);
        address.setUpdatedTime(LocalDateTime.now());
        updateById(address);
    }

    @Override
    public void modifyDeliveryAddress(Long id, DeliveryAddressDTO addressDTO) {
        if (addressDTO.getIsDefault() == 1) {
            lambdaUpdate()
                    .eq(DeliveryAddress::getUserId, UserContext.getId())
                    .set(DeliveryAddress::getIsDefault, 0)
                    .update();
        }
        lambdaUpdate()
                .eq(DeliveryAddress::getId, id)
                .set(DeliveryAddress::getReceiverName, addressDTO.getReceiverName())
                .set(DeliveryAddress::getReceiverPhone, addressDTO.getReceiverPhone())
                .set(DeliveryAddress::getProvince, addressDTO.getProvince())
                .set(DeliveryAddress::getCity, addressDTO.getCity())
                .set(DeliveryAddress::getDistrict, addressDTO.getDistrict())
                .set(DeliveryAddress::getDetailAddress, addressDTO.getDetailAddress())
                .set(DeliveryAddress::getIsDefault, addressDTO.getIsDefault())
                .set(DeliveryAddress::getUpdatedTime, LocalDateTime.now())
                .update();
    }

    @Override
    public DeliveryAddressVo getDefaultDeliveryAddress() {
        DeliveryAddress deliveryAddress = lambdaQuery()
                .eq(DeliveryAddress::getUserId, UserContext.getId())
                .eq(DeliveryAddress::getIsDefault, 1)
                .one();
        DeliveryAddressVo deliveryAddressVo = new DeliveryAddressVo();
        if (deliveryAddress == null) {
            return null;
        }
        BeanUtils.copyProperties(deliveryAddress, deliveryAddressVo);
        return deliveryAddressVo;
    }

    @SneakyThrows
    @Override
    public String getChinaCities() {
        Resource resource = resourceLoader.getResource("classpath:json/ChinaCities.json");
        InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
        return FileCopyUtils.copyToString(reader);
    }
}




